#pragma once
#include <sys/select.h>
#include <array>
/* According to earlier standards */
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <poll.h>
#include "Socket.hpp"
class PollTcpServer
{
    const int mx = 100;
public:
    PollTcpServer(int port)
        : _listenfd(new TcpSocket()), _port(port)
    {
        memset(_fds, -1, sizeof(_fds));
        _listenfd->BuiltListenSockfd(port, 10);
        _fds[0].fd = _listenfd->GetSocket(); // 将监听fd也一起放入
        _fds[0].events = POLLIN; // 将监听fd也一起放入
    }

    void Loop()
    {
        while (1)
        {
            int mxfd = 0;
            for (int i = 0; i < mx; i++)
            {
                
            }
            int n = poll(_fds, mx, -1/*{0,0}非阻塞 nullptr阻塞 具体时间*/);
            for (int i = 0; i < mx; i++)
            {
                if (_fds[i].fd == -1)
                    continue;
                int events = _fds[i].revents;
                if (events & POLLIN)
                {
                    if(_fds[i].fd == _listenfd->GetSocket())
                    {
                        std::string ip;
                        uint16_t port;
                        int fd = _listenfd->AcceptConnection(&ip, &port);
                        for(int j = 0; j < mx; j++)
                        {
                            if(_fds[j].fd == -1)
                            {
                                _fds[j].fd = fd;
                                _fds[j].events = POLLIN;
                                break;
                            }
                        }
                    }
                    else
                    {
                        char buffer[1024];
                        int n = read(_fds[i].fd, buffer,sizeof(buffer));
                        if(n > 0)
                        {
                            buffer[n] = 0;
                            std::cout << "fd : " << _fds[i].fd << " # " << buffer << std::endl;
                            std::string ret = buffer;
                            ret += "收到";
                            write(_fds[i].fd, ret.c_str(), ret.size());
                        }
                        else
                        {
                            close(_fds[i].fd);
                            _fds[i].fd = -1;
                        }
                    }
                }
            }
        }
    }

    ~PollTcpServer()
    {
        _listenfd->CloseSocket();
        delete _listenfd;
        _listenfd = nullptr;
    }
    
private:
    struct pollfd _fds[100];
    uint16_t _port;
    TcpSocket *_listenfd;
};